package locate

import (
	"ones-objects/lib/mq"
	"ones-objects/config"
	"strconv"
	"os"
)

/**
 * 监听api发过来的对象确认信息，如果在当前服务器存在，则返回服务器地址
 */
func StartLocate()  {
	conf := mq.RabbitConf{
		Dsn: config.GetString(config.RABBITMQ_DSN),
		Queue: config.GetString(config.RABBITMQ_QUEUE_DATA),
		Exchange: config.RABBITMQ_EXCHANGE_DATA,
	}
	mq := mq.New(conf)
	defer mq.Close()

	content := config.GetString(config.DATAS_API_LISTENER)

	msgs := mq.Consume()
	for msg := range msgs {
		object,err := strconv.Unquote(string(msg.Body))
		if err != nil {
			panic(err)
		}
		if Locate(config.GetString(config.OBJECTS_LOCAL_PATH) + config.OBJECTS_PATH + object) {
			mq.Send(msg.ReplyTo, content)
		}
	}

}

func Locate(name string) bool {
	_,err := os.Stat(name)
	return !os.IsNotExist(err)
}